<template>
  <div>
    <BasicTable @register="registerTable">
      <template #headerTop>
        <Alert v-if="checkedKeys.length > 0" type="info" show-icon class="relative">
          <template #message>
            <div>
              <span>已选中{{ checkedKeys.length }}条记录</span>
              <div class="absolute top-4px right-10px">
                <Tooltip title="删除">
                  <Button type="text" @click="handleSelectedDelete">
                    <Icon :icon="ICON.DELETE" color="#0960bd" />
                  </Button>
                </Tooltip>
              </div>
            </div>
          </template>
        </Alert>
      </template>
      <template #toolbar>
        <Button type="primary" @click="addQueues">添加新的队列</Button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: ICON.EDIT,
                tooltip: {
                  title: '编辑',
                  placement: 'top',
                },
                onClick: openModal.bind(null, true, { record }),
              },
              {
                icon: ICON.CHECK,
                tooltip: {
                  title: '查看',
                  placement: 'top',
                },
                onClick: handleDetail.bind(null, record),
              },
              {
                icon: ICON.DELETE,
                tooltip: {
                  title: '删除',
                  placement: 'top',
                },
                onClick: handleDelete.bind(null, record),
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>
    <QueuesModel @register="register" @success="success" />
    <PublicDrawer
      @register="registerDrawer"
      :show-tabs="['detail']"
      @update-desc-data="handleUpdateDescData"
    />
  </div>
</template>

<script lang="ts" setup>
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getQueuesList,
    deleteQueues,
    getQueues,
  } from '/@/api/thingsborad/settings/BasicSetting/basicSetting';
  import { getBasicColumns, searchSchema, keyWordsTranslation, detailSchema } from './queue.data';
  import { tableFormStyleSetting, tableStyleSetting } from '/@/settings/thingsBoardDesign';
  import QueuesModel from './QueuesModel.vue';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import Icon from '/@/components/Icon';
  import { ICON } from '/@/enums/iconEnum';
  import { Alert, Tooltip, Button } from 'ant-design-vue';
  import PublicDrawer from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.vue';
  import { ENTITY_TYPE } from '/@/components/thingsborad/sharedComponents/modules/PublicDrawer/index.data';
  import { useDrawer } from '/@/components/Drawer';
  import _ from 'lodash';
  import { ref } from 'vue';
  const checkedKeys = ref<any>([]);
  const [register, { openModal }] = useModal();
  const { createConfirm } = useMessage();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerTable, { reload, setProps }] = useTable({
    title: '队列',
    columns: getBasicColumns,
    api: getQueuesList,
    ...tableStyleSetting,
    beforeFetch: (val) => {
      if (!val.field) {
        (val.field = 'createdTime'), (val.order = 'DESC');
      }
      let params: Recordable = {
        page: val.page - 1,
        pageSize: val.pageSize,
        sortOrder: val.order === 'ascend' ? 'ASC' : 'DESC',
        sortProperty: val.field,
        serviceType: 'TB_RULE_ENGINE',
      };
      if (val?.textSearch) {
        params.textSearch = val.textSearch;
      }
      return params;
    },
    afterFetch: (res) => {
      let list: Array<Recordable> = [];
      if (res.length != 0) {
        res.forEach((item: Recordable) => {
          item.id = item.id.id;
          item.submitStrategy = keyWordsTranslation[item.submitStrategy.type];
          item.processingStrategy = keyWordsTranslation[item.processingStrategy.type];
          list.push(item);
        });
      }
      return list;
    },

    formConfig: {
      layout: 'horizontal',
      schemas: searchSchema,
      showAdvancedButton: false,
      ...tableFormStyleSetting,
      actionColOptions: {
        md: { span: 8, offset: 8 },
        lg: { span: 6, offset: 12 },
        xl: { span: 4, offset: 16 },
        xxl: { span: 4, offset: 16 },
      },
      submitFunc: async () => {
        reload();
      },
    },
    rowKey: 'id',
    rowSelection: {
      type: 'checkbox',
      selectedRowKeys: checkedKeys,
      onSelect: onSelect,
      onSelectAll: onSelectAll,
    },
  });
  // 多选
  function onSelect(record: Recordable, selected: boolean) {
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, record.id];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id: string) => id !== record.id);
    }
  }
  function onSelectAll(selected: boolean, _selectedRows: Recordable[], changeRows: Recordable[]) {
    const changeIds = changeRows.map((item: Recordable) => item.id);
    if (selected) {
      checkedKeys.value = [...checkedKeys.value, ...changeIds];
    } else {
      checkedKeys.value = checkedKeys.value.filter((id: string) => {
        return !changeIds.includes(id);
      });
    }
  }
  //多选删除
  function handleSelectedDelete() {
    createConfirm({
      iconType: 'info',
      title: `确定要删除${checkedKeys.value.length}个队列吗？`,
      content: '请注意：确认后，所有选定队列都将被删除，无法访问。',
      onOk: async () => {
        setProps({ loading: true });
        for (const item of checkedKeys.value) {
          let paramsURL = '/' + item;
          try {
            await deleteQueues(paramsURL);
            reload();
          } catch (error) {
            console.error('删除失败', error);
          }
        }
        checkedKeys.value = [];
      },
    });
  }
  function handleDelete(record: Recordable) {
    createConfirm({
      iconType: 'info',
      title: `确定要删除 '${record.name}'队列吗？`,
      content: '请注意：确认后，队列和所有相关数据将不可恢复。',
      onOk: async () => {
        await deleteQueues('/' + record.id);
        reload();
      },
    });
  }
  function addQueues() {
    openModal();
  }
  function handleDetail(record: Recordable) {
    openDrawer(true, {
      entityType: ENTITY_TYPE.QUEUES,
      entityId: record.id,
      title: record.name,
      api: getQueues,
      detailSchema: detailSchema,
      params: '/' + record.id,
    });
  }

  async function handleUpdateDescData(value: Recordable) {
    value.batchSize = value.submitStrategy.batchSize;
    value.retries = value.processingStrategy.retries;
    value.failurePercentage = value.processingStrategy.failurePercentage;
    value.pauseBetweenRetries = value.processingStrategy.pauseBetweenRetries;
    value.maxPauseBetweenRetries = value.processingStrategy.maxPauseBetweenRetries;
    if (value.additionalInfo) {
      value.customProperties = value.additionalInfo.customProperties;
      value.description = value.additionalInfo.description;
    }
    value.submit = keyWordsTranslation[value.submitStrategy.type];
    value.processing = keyWordsTranslation[value.processingStrategy.type];
  }
  function success(key: string) {
    if (key == 'add') {
      reload({ sortInfo: { field: 'createdTime', order: 'DESC' } });
    } else {
      reload();
    }
  }
</script>
